//
//  Shader.fsh
//  Renderbunny
//
//  Created by Holmes Futrell on 1/20/11.
//  Copyright 2011 Holmes Futrell. All rights reserved.
//

uniform sampler2D normalsSpecSampler;
uniform sampler2D depthSampler;

uniform vec2 imageSize;
uniform float zNear, zFar;

void main()
{

	vec3 lightColor = vec3(1.0, 1.0, 1.0); // make light color a uniform
	vec3 light = normalize(vec3(1.0, 1.0, 1.0)); // make light direction a uniform
	float D = -(2.0 * zFar * zNear) / (zFar - zNear); // make me a uniform
	float C = -(zFar + zNear) / (zFar - zNear);		  // make me a uniform

	// lookup normal + specular
	vec4 normal_spec	= texture2D(normalsSpecSampler, gl_FragCoord.xy / imageSize);
	
	// lookup depth
	float depth			= 2.0 * texture2D(depthSampler, gl_FragCoord.xy / imageSize).r - 1.0;
	
	// grag specular component
	float specularPower = normal_spec.a;

	// normalize normal
	vec3 normal			= normalize(normal_spec.rgb - 0.5);
	
	// compute eye-sace position
	vec3 worldPos;
	worldPos.xy = ( gl_FragCoord.xy * (2.0 / imageSize) - 1.0 ) / zNear; // make (2.0 / imageSize) a uniform
	worldPos.z  = -D / (depth + C);
	worldPos = normalize(worldPos);

	// this is the (tiny!) work done per light
	vec3 diffuse			= lightColor * max( 0.0, dot(normal, light) );
	vec3 halfV				= normalize( light - worldPos );
	float halfVdotN			= max(0.0, dot(halfV, normal));
	vec3 spec				= lightColor * pow(halfVdotN, (specularPower * 300.0)); // make 300 a uniform

	// write outputs
   	gl_FragData[0] = vec4(diffuse, 1.0);
   	gl_FragData[1] = vec4(spec, 1.0);

}